<template>
  <div class="onesche-container">
    <!-- 显示属性集 -->
    <div class="section-title">
      <h2> {{ rsData.rname }}</h2>
    </div>
    <div class="attributes">
      {{ filteredAtAttributes }}
    </div>

    <!-- 显示函数依赖 -->
    <div class="dependencies">
      {{ functionDependencies }}
    </div>
    <div class="button-container">
      <el-button type="primary" icon="el-icon-back" @click="gotomain">返回</el-button>
    </div>
    <br>
   <!-- 新建数据库按钮 -->
   <el-button type="primary" @click="showDatabaseInput">新建数据库</el-button>

<!-- 数据库名称输入框 -->
<el-dialog :visible.sync="showDialog" title="新建数据库">
  <el-form>
    <el-form-item label="数据库名称">
      <el-input v-model="newDatabaseName"></el-input>
    </el-form-item>
  </el-form>
  <span slot="footer" class="dialog-footer">
    <el-button @click="showDialog = false">取消</el-button>
    <el-button type="primary" @click="createDatabase">确定</el-button>
  </span>
</el-dialog>

 <!-- 元组输入表格 -->
 <el-table v-if="databaseName && filteredAtAttributesArray.length > 0" :data="tuples" style="width: 100%">
      <el-table-column v-for="(attribute, index) in filteredAtAttributesArray" :key="index" :label="attribute.value">
        <template slot-scope="scope">
          <el-input v-model="scope.row[attribute.value]"></el-input>
        </template>
      </el-table-column>
      <el-table-column label="操作">
        <template slot-scope="scope">
          <el-button type="danger" size="mini" @click="removeTuple(scope.$index)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-button v-if="databaseName && filteredAtAttributesArray.length > 0" type="primary" @click="addTuple">添加元组</el-button>
    <el-button v-if="databaseName && filteredAtAttributesArray.length > 0" type="primary" @click="sendTuple">保存数据库</el-button>
  
    </div>
</template>

<script>
import { mapGetters } from 'vuex';
import { getrf } from '@/api/rs';
import { createdb } from '@/api/db';
import { addtp } from '@/api/dbt';
export default {
    name: 'onesche',
    created() {
        this.read();

    },
    computed: {
        ...mapGetters([
            'token',
            'Rid'
        ])
        ,
        filteredAtAttributes() {//属性集过滤非空元素
      const attributes = [];
      for (let key in this.rsData.at) {
        if (this.rsData.at.hasOwnProperty(key) && key >= 'ua' && key <= 'um' && this.rsData.at[key] !== null&& key!='uid') {
          attributes.push(`${this.rsData.at[key]}`);
          //attributes.push(`${key}: ${this.rsData.at[key]}`);
        }
      }
      return attributes.length > 0 ? `属性集: ${attributes.join(', ')}` : '';
    },
    filteredAtAttributesArray() {
      const attributes = [];
      for (let key in this.rsData.at) {
        if (this.rsData.at.hasOwnProperty(key) && key >= 'ua' && key <= 'um' && this.rsData.at[key] !== null&& key!='uid') {
          attributes.push({ key, value: this.rsData.at[key] });
        }
      }
      return attributes;
    },
    functionDependencies() {//函数依赖集过滤非空元素
      const dependencies = [];
      for (let key in this.rsData.fd) {
        if (this.rsData.fd.hasOwnProperty(key)) {
          if (key.endsWith('l') && this.rsData.fd[key] !== null) {
            const rightKey = key.replace('l', 'r');
            if (this.rsData.fd[rightKey] !== null) {
              dependencies.push(`${this.rsData.fd[key]} -> ${this.rsData.fd[rightKey]}`);
            }
          }
        }
      }
      return dependencies.length > 0 ? `函数依赖集: ${dependencies.join(', ')}` : '';
    }
  

  },

    data() {
        return {
            rsData:[],
            keyword: '',
            showDialog: false,
            newDatabaseName: '',
            databaseName: '',
            tuples: [],
            dbid:'',
            rtuples:[],
            num:0

        }
    },

    methods: {
        read() {
          console.log(typeof getrf); // 应该输出 "function"
          getrf(this.Rid).then(response => {
                this.rsData = response.data.rs;
                console.log(this.rsData)
            }).catch(error => {
                console.log(error);
            })
        },
        showDatabaseInput() {
      this.showDialog = true;
    },
    createDatabase() {
      if (this.newDatabaseName.trim()) {
        this.databaseName = this.newDatabaseName;
        createdb(this.Rid,this.databaseName).then(response => {
              this.dbid = response.data.dbid;
          }).catch(error => {
              console.log(error);
          })

        this.showDialog = false;
        this.addTuple(); // 初始化时添加一个空元组
      } else {
        this.$message.error('请输入数据库名称');
      }
    },
    addTuple() {
      if (!this.filteredAtAttributesArray || this.filteredAtAttributesArray.length === 0) {
        console.error('filteredAtAttributesArray is not properly initialized');
        return;
      }

      const tuple = {};
      this.filteredAtAttributesArray.forEach(attribute => {
        tuple[attribute.value] = ''; // 使用属性值作为键
      });
     
      this.tuples.push(tuple);
      this.num++; // 增加计数器
      console.log(this.tuples[0])
      //addtp(this.tuples)
      
    },
    removeTuple(index) {
      this.tuples.splice(index, 1);
    },
    sendTuple() {//数据库元组传输到后端
      this.rtuples = [];
      // 遍历每个 tuple
      this.tuples.forEach(tuple => {
        const rtuple = {
          dbid: this.dbid,
          ta: null,
          tb: null,
          tc: null,
          td: null,
          te: null,
          tf: null,
          tg: null,
          th: null,
          ti: null,
          tj: null,
          tk: null,
          tl: null,
          tn: null,
          tm: null
        };

        // 根据 filteredAtAttributesArray 的顺序赋值
        this.filteredAtAttributesArray.forEach((attribute, index) => {
          const attributeValue = tuple[attribute.value];
          if (attributeValue !== undefined && attributeValue !== '') {
            rtuple[`t${String.fromCharCode(97 + index)}`] = attributeValue; // a=97 in ASCII
          }
        });

        // 将生成的 rtuple 添加到 rtuples 数组中
        this.rtuples.push(rtuple);
      });
      console.log(this.num)
      console.log("看看计数器")

      console.log(this.rtuples); // 输出结果
      addtp(this.rtuples).then(response => {
        this.$message({
          message: '新建数据库成功',
          type: 'success'
        })
        setTimeout(() => {
      this.$router.push('/DBII/alldb');//TODO 转到数据库界面
    }, 2000); // 3000 毫秒 = 3 秒
               

            }).catch(error => {
                console.log(error);
            })

    },
    gotomain(){
      this.$router.push('/SCEI/allsche')
    }
   
       }
}






</script>
<style lang="scss" scoped>
.onesche {
    &-container {
        margin: 30px;
        font-family: Arial, sans-serif;
    }
}


.section-title {
  margin: 20px 0;
  padding-bottom: 5px;
  border-bottom: 2px solid #ddd;
}

.attributes, .dependencies {
  margin-left: 20px;
  margin-top: 10px;
  padding: 10px;
  background-color: #f9f9f9;
  border: 1px solid #ddd;
}
.rname {
    font-size: 20px;
    color: rgb(0, 0, 0);
    font-family: Arial, sans-serif;
}

.update {
    font-size: 15px;
    color: rgb(21, 21, 197);
    font-family: Arial, sans-serif;
}

.author {
    font-size: 13px;
}
.button-container {
  position: absolute;
  top: 20px; /* 距离顶部的距离 */
  right: 20px; /* 距离右边的距离 */
}

.el-icon-view {
    font-size: 12px;
}

.el-icon-magic-stick {
    font-size: 12px;
}
</style> 